package com.eeepay.eeepay_v2.activity;

import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.TradeCollectListAdapter;
import com.eeepay.eeepay_v2.model.TradeQueryCri;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshBase;
import com.eeepay.v2_library.pulltorefresh.PullToRefreshListView;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ScreenSwitch;

import java.util.Arrays;
import java.util.List;

import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/5/4 0004.
 * 交易超级查询汇总
 */
public class TradeCollectActivity extends ABBaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {

    private final int AGENT_CONNECT = 1;
    private final int PRODUCT_CONNECT = 2;
    private TextView tv_back, tv_company;
    private RadioGroup top_group;//代理商汇总、产品汇总
    private String flag;//区分是1代理商汇总还是2产品汇总
    private PullToRefreshListView lv_content;
    private TextView tv_countSum, tv_moneySum;
    private TextView tv_collectName;
    private TradeCollectListAdapter adapter;
    private List<TransProto.AggregateInfo> agentDatas, productDatas;

    //交易超级查询条件
    private TradeQueryCri tradeQueryCri;

    private String agentTotalCount;
    private String agentTotalAmount;

    private String bpTotalCount;
    private String bpTotalAmount;

    private int agentCurrPage = 1;
    private int hpCurrPage = 1;
    private int ageTotal, proTotal;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_trade_collect;
    }

    @Override
    protected void initWidget() {
        tradeQueryCri = (TradeQueryCri) bundle.getSerializable(Constant.TRADE_QUERY_CRI);

        tv_back = getViewById(R.id.tv_back);
        top_group = getViewById(R.id.radio_group);
        lv_content = getViewById(R.id.lv_content);
        tv_countSum = getViewById(R.id.tv_count_sum);
        tv_moneySum = getViewById(R.id.tv_money_sum);
        tv_collectName = getViewById(R.id.tv_collect_name);

        adapter = new TradeCollectListAdapter(mContext);
        lv_content.setAdapter(adapter);

        sendHttpRequest(AGENT_CONNECT);

    }

    @Override
    protected void eventOnClick() {
        tv_back.setOnClickListener(this);
        top_group.setOnCheckedChangeListener(this);
        top_group.check(top_group.getChildAt(0).getId());

        lv_content.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
        lv_content.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                if ("1".equals(flag)) {
                    if (ageTotal > agentCurrPage * 10) {
                        agentCurrPage++;
                        sendHttpRequest(AGENT_CONNECT);
                    } else {
                        showToast("已经是最后一页了");
                        if (lv_content.isRefreshing()) {
                            lv_content.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    lv_content.onRefreshComplete();
                                }
                            }, 500);
                        }
                    }

                } else {
                    if (proTotal > hpCurrPage * 10) {
                        hpCurrPage++;
                        sendHttpRequest(PRODUCT_CONNECT);
                    } else {
                        showToast("已经是最后一页了");
                        if (lv_content.isRefreshing()) {
                            lv_content.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    lv_content.onRefreshComplete();
                                }
                            }, 500);
                        }
                    }

                }
            }
        });
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        super.sendHttpRequest(taskId);
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId
                , new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                TransProto.TransBySupperReq request = getRequest(taskId);
                if(TextUtils.equals("1", flag)){
                    request.pageNo = agentCurrPage;
                }else {
                    request.pageNo = hpCurrPage;

                }
                TransApiServiceGrpc.TransApiServiceBlockingStub stub = TransApiServiceGrpc.newBlockingStub(channel);
                TransProto.TransAggregateRes res = stub.queryTransAggregate(request);
                return res;
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (lv_content.isRefreshing()) {
                    lv_content.onRefreshComplete();
                }
                if(result == null){
                    showToast("查询失败");
                    return;
                }
                TransProto.TransAggregateRes response = (TransProto.TransAggregateRes) result;
                if(!response.resMsg.status){
                    showToast(response.resMsg.msg);
                    return;
                }
                tv_countSum.setText(response.transTotalCheque + "笔");
                tv_moneySum.setText(response.transTotalAmount + "元");
                switch (taskId){
                    case AGENT_CONNECT:
                        ageTotal = response.total;
                        agentTotalCount = response.transTotalCheque;
                        agentTotalAmount = response.transTotalAmount;
                        agentDatas = Arrays.asList(response.aggregateInfo);
                        adapter.setList(agentDatas);
                        break;
                    case PRODUCT_CONNECT:
                        proTotal = response.total;
                        bpTotalCount = response.transTotalCheque;
                        bpTotalAmount = response.transTotalAmount;
                        productDatas = Arrays.asList(response.aggregateInfo);
                        adapter.setList(productDatas);
                        break;
                }
            }
        });
    }

    private TransProto.TransBySupperReq getRequest(int aggregate){
        TransProto.TransBySupperReq request = new TransProto.TransBySupperReq();
        request.agentNode = tradeQueryCri.getAgentNode();
        request.agentNameOrNo = tradeQueryCri.getAgentName();
        request.transBeginTime = tradeQueryCri.getTradeStartTime();
        request.transEndTime = tradeQueryCri.getTradeEndTime();
        request.transBeginAmount = tradeQueryCri.getTradeMinMoney();
        request.transEndAmount = tradeQueryCri.getTradeMaxMoney();
        request.cardType = tradeQueryCri.getCardType();
        request.transCardNo = tradeQueryCri.getCardNum();
        request.merPhone = tradeQueryCri.getPhone();
        request.merNameOrNo = tradeQueryCri.getMerchantName();
        request.posType = tradeQueryCri.getDeviceName();
        request.transStatus = tradeQueryCri.getTradeStatus();
        request.isInclude = "1";
        if(TextUtils.isEmpty(tradeQueryCri.getTime())){
            request.registerBeginTime = tradeQueryCri.getIntoStartTime();
            request.registerEndTime = tradeQueryCri.getIntoEndTime();
        }else {
            request.time = tradeQueryCri.getTime();
        }
        request.aggregate = aggregate + "";
        return request;
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId){
            case R.id.btn_1://代理商汇总
                flag = "1";
                tv_collectName.setText("代理商名称");
                if(agentDatas != null){
                    tv_countSum.setText(agentTotalCount + "笔");
                    tv_moneySum.setText(agentTotalAmount + "元");
                    adapter.setList(agentDatas);
                }
                break;
            case R.id.btn_2:
                flag = "1";
                tv_collectName.setText("产品名称");
                if(productDatas == null){
                    sendHttpRequest(PRODUCT_CONNECT);
                }else {
                    tv_countSum.setText(bpTotalCount + "笔");
                    tv_moneySum.setText(bpTotalAmount + "元");
                    adapter.setList(productDatas);
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_back:
                ScreenSwitch.finish(mContext);
                break;
        }
    }
}
